import TableParseInterface from '../interface/TableParseInterface'
import {
  TableInterface,
  TableConfig,
  ColumnItem,
  headerParseResult,
  BodyParseResult
} from '../interface/typedefs'
class SimpleTableParser extends TableParseInterface {
  public colWidths: number[] = [] //存储父列的宽度
  public dataProps: string[] = [] //存储最下层列的属性名
  public dataWidths: number[] = [] //存储最下层列的宽度
  public imageList: string[] = [] //存储表格中所有图片的地址，用于绘制时候预加载图片
  // public imageMap: Map<string, string> = new Map() //存储表格中所有图片的地址和base64格式的图片

  constructor() {
    super()

    this.imageList = []
  }

  async parseTable(table: TableInterface): Promise<void> {
    this.columnsParseResult = null
    this.bodyParseResult = []

    if (this.onBeforeParse) this.onBeforeParse(table)
    const { columns, data, tableConfig } = table
    try {
      if (this.onBeforeParseHeader) {
        this.onBeforeParseHeader(columns)
      }
      this.columnsParseResult = await this.parseTableHeader(columns, tableConfig.header)
      if (this.onAfterParseHeader) {
        this.onAfterParseHeader(this.columnsParseResult)
      }
      if (this.onBeforeParseBody) {
        this.onBeforeParseBody(data)
      }
      this.bodyParseResult = await this.parseTableBody(data, tableConfig.body)
      if (this.onAfterParseBody) {
        this.onAfterParseBody(this.bodyParseResult)
      }
    } catch (error) {
      console.error(error)
      throw new Error('table parse error')
    }
  }

  private async parseTableHeader(
    columns: ColumnItem[],
    config: TableConfig['header'] = {}
  ): Promise<headerParseResult> {
    const parseResult: headerParseResult = {
      headerWidth: 0,
      headerHeight: 0,
      parseResult: {
        cellStyle: null,
        cellTextStyle: null,
        parseData: []
      }
    }

    // 合并基本配置
    const headerBaseConfig = {
      ...this.defaultHeaderConfig,
      ...config
    }
    const { cell, cellText, fit, border } = headerBaseConfig

    // 处理列宽高适配
    this.preprocessColumnWidths(columns, headerBaseConfig)
    this.preprocessColumnHeights(columns, headerBaseConfig)

    for (const [index, colItem] of columns.entries()) {
      console.log(index, colItem)
      //  0 { width: 100, height: 40, label: '姓名', prop: 'name' }
      // const { width, height, label, prop, wordBreak = 0, children = [] } = colItem
      // 如果有children 一直遍历
      // if(colItem.children && colItem.children.length > 0) {

      // }

      // this.handleCell(cell, colItem)
      // this.handleCellText(cellText, label, wordBreak)
    }
    return parseResult
  }
  private async parseTableBody(data: any[], config: TableConfig['body']): Promise<BodyParseResult> {
    console.log(config, data)
    return []
  }

  private preprocessColumnWidths(columns: ColumnItem[], config: TableConfig['header']): void {
    const calculateWidths = (col: ColumnItem) => {
      const { width = null, wordBreak, label } = col
      const { minWidth = 0, padding } = config?.cell ?? {}
      const { fontSize, fontFamily } = config?.cellText ?? {}

      if (col.children && col.children.length > 0) {
        col.children.forEach((child) => {
          calculateWidths(child)
        })
      }

      if (!width && this.ctx) {
        col.width = this.calculateCellWidth(
          this.ctx,
          label,
          minWidth,
          wordBreak,
          fontSize,
          fontFamily,
          padding
        )
      }
    }
    columns.forEach((col) => {
      calculateWidths(col)
    })
  }
  private preprocessColumnHeights(columns: ColumnItem[], config: TableConfig['header']): void {
    const calculateHeights = (col: ColumnItem) => {
      const { height = null, label, wordBreak } = col
      const { minHeight = 0, padding } = config?.cell ?? {}
      const { fontSize, lineHeight } = config?.cellText ?? {}

      if (!height) {
        col.height = this.calculateCellHeight(
          label,
          minHeight,
          fontSize,
          wordBreak,
          padding,
          lineHeight
        )
      }
    }

    columns.forEach((col) => {
      if (col.children && col.children.length > 0) {
        col.children.forEach((child) => {
          calculateHeights(child)
        })
      } else calculateHeights(col)
    })
  }
}

export default SimpleTableParser
